"use client"

import { useCallback, useEffect, useRef, useState } from "react"

type EditTextProps = {
    text: string[]
}
const EditText = ({ text }: EditTextProps) => {
    const [value, setValue] = useState("");
    const index = useRef<number>(0);
    const [time, setTime] = useState<NodeJS.Timeout>();
    const [_, setEditTime] = useState<NodeJS.Timeout>();
    const [edit, setEdit] = useState(true);
    const [state, setState] = useState("wait");
    useEffect(() => {
        const time = setTimeout(() => {
            setEdit(!edit);
        }, 500)
        setEditTime(time);
        return () => clearTimeout(time);
    }, [edit]);
    useEffect(() => {
        if (state === "wait") {
            if (text.length === 0) return;
            setState("begin");
            return;
        }
        if (state === "end") {
            setTime(setTimeout(() => {
                setState("deleting");
            }, 3000))
            return;
        }
        if (state === "begin") {
            if (value == text[index.current]) {
                setState("end");
                return;
            }
            setTime(setTimeout(() => {
                setValue(value + text[index.current][value.length]);
            }, 100));
        }
        if (state === "deleting") {
            if (!value) {
                index.current = index.current + 1;
                index.current = index.current === text.length ? 0 : index.current;
                setState("begin");
                return;
            }
            setTime(setTimeout(() => {
                setValue(value.slice(0, value.length - 1));
            }, 30));
        }
    }, [state, text, value]);
    useEffect(() => {
        return () => clearTimeout(time);
    }, [time]);
    if (!text.length) return null;
    return <span>{value}<span className={`border-r-2 border-r-black ${edit ? 'opacity-0' : 'opacity-100'} `} /></span>
}
export default EditText